/* eslint-disable @typescript-eslint/no-unused-vars */
import { useMyLocales } from '@/hooks/useMyLocales';
import { getHttpHeaders } from '@/utils/request';
import { isValidImageExtension, isValidPdfExtension } from '@/utils/tools';
import {
  DownloadOutlined,
  RotateLeftOutlined,
  RotateRightOutlined,
  SwapOutlined,
  UploadOutlined,
  ZoomInOutlined,
  ZoomOutOutlined,
} from '@ant-design/icons';

import { Button, Image, Modal, Space, Tooltip, Upload, message } from 'antd';
import type {
  UploadChangeParam,
  UploadFile,
  UploadProps,
} from 'antd/es/upload';
import { isEmpty } from 'lodash-es';
import { FC, ReactNode, useEffect, useState } from 'react';
import FilePreview from '../FilePreview';

import { fileDownload } from '@/utils/file';
import './index.css';

type Props = {
  ids?: string[] | string;
  multiple?: boolean;
  children?: ReactNode;
  onChange?: (
    info: Pick<UploadChangeParam<UploadFile>, 'file' | 'fileList'>,
  ) => void;
  onComplete?: (info: Pick<UploadChangeParam<UploadFile>, 'fileList'>) => void;
  disabled?: boolean;
  showUploadList?: boolean;
  action?: string;
  name?: string;
  className?: any;
} & Partial<Pick<UploadProps, 'maxCount'>>;

export const FileUpload: FC<Props> = (props) => {
  const { fileUploadButton, fileDownloadLang, supplierDownloading } =
    useMyLocales();
  const {
    ids,
    onChange,
    onComplete,
    children,
    multiple,
    action,
    name,
    className,
    ...restProps
  } = props;
  const _ids: string[] =
    (typeof ids === 'string' ? [ids] : ids)?.filter((id) => !isEmpty(id)) ?? [];
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [open, setOpen] = useState(false);
  const [filePreview, setFilePreview] = useState({
    fileUid: '',
    fileName: '',
    fileUrlPreview: '',
  });
  const [show3, setShow3] = useState(false);
  const [imgIndex, setImgIndex] = useState(0);
  const [headers] = useState(getHttpHeaders());
  useEffect(() => {
    // if (!_ids?.length || _ids.join(",") === fileList.map((x) => x.uid).join(",")) {
    //   return;
    // }
    if (!_ids?.length) {
      return;
    }
    // postFileFileListWrapper(_ids).then((res) => {
    //   const files = res?.data ?? [];
    //   setFileList(
    //     files.map((file) => ({
    //       uid: file.id!,
    //       name: file.fileName!,
    //       url: file.url!,
    //       fileSuffix: file.extensionName!,
    //     })),
    //   );
    // });
  }, []);
  const handleChange: UploadProps['onChange'] = ({
    file,
    fileList: newFileList,
  }) => {
    // console.warn(file, newFileList);
    const _newFileList: UploadFile[] = newFileList.map((file) => {
      if (file.status === 'done' && file.response.data) {
        return {
          uid: file.response.data.id,
          name: file.name,
          url: file.response.data.url,
        };
      }
      return file;
    });
    setFileList(_newFileList);
    onChange?.({
      file,
      fileList: _newFileList.filter((file) => !file.status),
    });
    if (!_newFileList.some((file) => file.status)) {
      onComplete?.({ fileList: _newFileList });
    }
  };

  const handlePreview = async (file: UploadFile) => {
    if (isValidImageExtension(file.name)) {
      setFilePreview({
        fileUid: file.uid,
        fileName: file.name,
        fileUrlPreview: file.url ?? '',
      });
      setShow3(true);
      return;
    }

    if (isValidPdfExtension(file.name)) {
      setFilePreview({
        fileUid: file.uid,
        fileName: file.name,
        fileUrlPreview: file.url ?? '',
      });
      setOpen(true);
      return;
    }

    const key = Math.random();
    message.open({
      key,
      type: 'loading',
      duration: 0,
      content: supplierDownloading,
    });
    fileDownload(
      `${process.env.API_PREFIX_JCI}/api/File/Download/${file.uid}`,
      file.name,
    ).finally(() => {
      message.destroy(key);
    });
  };

  const onDownload = async ({ uid, name }: { uid: string; name: string }) => {
    const key = Math.random();
    message.open({
      key,
      type: 'loading',
      duration: 0,
      content: supplierDownloading,
    });
    fileDownload(
      `${process.env.API_PREFIX_JCI}/api/File/Download/${uid}`,
      name,
    ).finally(() => {
      message.destroy(key);
    });
  };

  return (
    <>
      <Upload
        className={className ? className : undefined}
        name={name ? name : undefined}
        action={
          action ? action : `${process.env.API_PREFIX_JCI}/api/File/Upload`
        }
        headers={headers}
        listType="text"
        fileList={fileList}
        beforeUpload={(file) => {
          if (file.size === 0) {
            message.error('请勿上传空文件！');
            return Upload.LIST_IGNORE;
          }
        }}
        multiple={multiple}
        onChange={handleChange}
        onPreview={handlePreview}
        {...restProps}
      >
        {!restProps.disabled ? (
          children ? (
            children
          ) : (
            <Button icon={<UploadOutlined />}>{fileUploadButton}</Button>
          )
        ) : null}
      </Upload>

      {isValidPdfExtension(filePreview.fileName) ? (
        <Modal
          title={
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                margin: '0px 180px',
              }}
            >
              <div>{filePreview.fileName}</div>
              <div>
                <Button
                  type="primary"
                  onClick={() =>
                    onDownload({
                      uid: filePreview.fileUid,
                      name: filePreview.fileName,
                    })
                  }
                >
                  {fileDownloadLang}
                </Button>
              </div>
            </div>
          }
          centered
          open={open}
          footer={null}
          onOk={() => setOpen(false)}
          onCancel={() => setOpen(false)}
          width={1200}
        >
          <FilePreview
            url={`${process.env.API_PREFIX_JCI + filePreview.fileUrlPreview}`}
          />
        </Modal>
      ) : isValidImageExtension(filePreview.fileName) ? (
        <Modal
          width={620}
          open={show3}
          centered
          footer={null}
          afterOpenChange={(open) => {
            setShow3(open);
          }}
          onCancel={() => {
            setShow3(false);
          }}
        >
          <Image.PreviewGroup
            preview={{
              // current: imgIndex,
              // onVisibleChange(value, prevValue, current) {
              //   setImgIndex(0);
              // },
              onChange(current, prevCurrent) {
                setImgIndex(current);
              },
              toolbarRender: (
                _,
                {
                  transform: { scale },
                  actions: {
                    onFlipY,
                    onFlipX,
                    onRotateLeft,
                    onRotateRight,
                    onZoomOut,
                    onZoomIn,
                  },
                },
              ) => {
                const item = fileList.filter((x) =>
                  isValidImageExtension(x.name),
                )[imgIndex];
                return (
                  <Space size={26}>
                    <DownloadOutlined
                      onClick={() =>
                        onDownload({ uid: item.uid, name: item.name ?? '' })
                      }
                    />
                    <SwapOutlined rotate={90} onClick={onFlipY} />
                    <SwapOutlined onClick={onFlipX} />
                    <RotateLeftOutlined onClick={onRotateLeft} />
                    <RotateRightOutlined onClick={onRotateRight} />
                    <ZoomOutOutlined
                      disabled={scale === 1}
                      onClick={onZoomOut}
                    />
                    <ZoomInOutlined
                      disabled={scale === 50}
                      onClick={onZoomIn}
                    />
                  </Space>
                );
              },
            }}
          >
            <div className="imgGroup">
              {fileList
                .filter((x) => isValidImageExtension(x.name))
                .map((x, index) => (
                  <div
                    key={x.uid}
                    className="imgOuter"
                    onClick={() => {
                      setImgIndex(index);
                    }}
                  >
                    <Tooltip title={x.name}>
                      <h4 className="imgTitle">{x.name}</h4>
                    </Tooltip>
                    <Image
                      key={x.uid}
                      width={120}
                      style={{
                        borderRadius: '5px',
                        padding: '6px',
                      }}
                      title={x.name}
                      src={`${process.env.API_PREFIX_JCI ?? ''}${x.url}`}
                    />
                  </div>
                ))}
            </div>
          </Image.PreviewGroup>
        </Modal>
      ) : null}
    </>
  );
};
